package cn.jdy.plugins.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.User;
import cn.jdy.authority.service.UserService;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.safe.SafeUtil;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.NginxPurgeCacheUtil;
import cn.jdy.framework.util.ValidationUtil;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.Files;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.entity.Notice;
import cn.jdy.plugins.entity.Works;
import cn.jdy.plugins.service.WorksService;

/**
 * @author yym
 * @title 主要工作控制类
 * @date 2016/02/26
 */
@Controller
@RequestMapping("/works")
public class WorksCtrl extends BaseCtrl {
	@Autowired
	private WorksService worksService;
	@Autowired
	private ConfService confService;
	@Autowired
	private UserService userService;
	
	/**
	 * 查询主要工作列表
	 * @param Works
	 * @return
	 */
	@RequestMapping("/index.html")
	public ModelAndView query(Works works) {
		ModelAndView mv = new ModelAndView("/works/worksList.jsp");
		//襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
		
		try {
			// 设置分页信息
			if (works.getiDisplayLength() == 0)
				works.setiDisplayLength(24); // 默认长度9
			if (works.getPageNo() <= 0)
				works.setPageNo(1); // 默认页数1
			works.setiDisplayStart((works.getPageNo() - 1)
					* works.getiDisplayLength()); // 显示起始索引
			works.setStatus("1");// 状态 0：无效，1：有效
			// 当关键字不为null并且不为空时，通过关键字全分类模糊查询
			// 反之，查询当前分页状态下的信息
			if (works.getKeyword() != null && !works.getKeyword().trim().isEmpty()) {
				mv.addObject("dataList",worksService.queryByLike(works, works.getKeyword()));
				mv.addObject("total", worksService.queryByLikeCount(works, works.getKeyword()));
			} else {
			
				mv.addObject("total", worksService.count(works));
				List<Works> dataList=worksService.query(works);
				/*** 统计还要多少要签收  开始 */
				for(Works x : dataList){
					String status = x.getSignStatus();
					String[] zhiduis = null;
					String[] assos = x.getAssociations();
					List<String> realAssos = new ArrayList<String>();
					List<String> notAssos = new ArrayList<String>();
					int len = 0,cnt=0;
					//公安-签收状态有别于特警，直接加入签收用户名，用,逗号分隔
					if(status!=null && status!=""){
						zhiduis = status.split(",");//已签收单位String数组
					}
					int tempIndex=0;
					for(int i=0;i<assos.length;i++){
						if((assos[i]!=null)){
		 					realAssos.add(cnt, assos[i]);
							//未签收
							if(zhiduis!=null && zhiduis.length>0){
								int tempCnt=0;
								for(int it=0;it<zhiduis.length;it++){
									if(!(assos[i].equals(zhiduis[it]))){
										tempCnt++;
									}
								}
								if(tempCnt==zhiduis.length){
									notAssos.add(tempIndex, assos[i]);
									tempIndex++;
								}
							}else{
								notAssos.add(cnt, assos[i]);
							}
							cnt++;
						}
					}
					 if(realAssos.size()>0){
						 x.setSignStatus(notAssos.size()+"");//用这个字段迭代到前台			
						}else{
							x.setSignStatus("-1");
						}
					
				}
				/***  统计还要多少要签收  结束*/
				mv.addObject("dataList", dataList);
			}
			mv.addObject("pageNo", works.getPageNo());
			mv.addObject("size", works.getiDisplayLength());
			mv.addObject("works", works);
			mv.addObject("key", works.getKeyword()); 
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return mv;
	}

	/**
	 * 主要工作详细内容页
	 * @param id
	 * @return
	 */
	@RequestMapping("/show-{id}.html")
	public ModelAndView queryDetail(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/works/worksDetail.jsp");
		//襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
		
		try {
			Works works = worksService.find(id);
			mv.addObject("works", works);
			// 增加一次查看
			if (works != null) {
				works.setReadTimes(works.getReadTimes() == null ? 1 : works
						.getReadTimes() + 1);
				worksService.update(works);
			}
			//特警
			String status = works.getSignStatus();
			String[] zhiduis = null;
//			String[] assos = works.getDepars().split(",");
			String[] assos = works.getAssociations();
			List<String> realAssos = new ArrayList<String>();
			List<String> notAssos = new ArrayList<String>();
			int len = 0,cnt=0;
			//公安-签收状态有别于特警，直接加入签收用户名，用,逗号分隔
			if(status!=null && status!=""){
				zhiduis = status.split(",");//已签收单位String数组
			}
			int tempIndex=0;
			for(int i=0;i<assos.length;i++){
				if((assos[i]!=null &&!(assos[i].equals(";")))){
 					realAssos.add(cnt, assos[i]);
					//未签收
					if(zhiduis!=null && zhiduis.length>0){
						int tempCnt=0;
						for(int it=0;it<zhiduis.length;it++){
							if(!(assos[i].equals(zhiduis[it]))){
								tempCnt++;
							}
						}
						if(tempCnt==zhiduis.length){
							notAssos.add(tempIndex, assos[i]);
							tempIndex++;
						}
					}else{
						notAssos.add(cnt, assos[i]);
					}
					cnt++;
				}
			}
			mv.addObject("realAssos", realAssos);//需要签收的单位gaj
			mv.addObject("signAssos", zhiduis);//已签收的支队名称 gaj
			mv.addObject("notAssos", notAssos);//未签收的支队名称 gaj
			mv.addObject("id", id);//未签收的支队名称 gaj
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "通知通报详细内容页异常", e);
		}
		return mv;
	}

	/**
	 * 首页初始化
	 * @param Works
	 * @return
	 */
	@RequestMapping("/ind")
	@ResponseBody
	public Map<String, Object> queryN(Works works) {
		Map<String, Object> resp = new HashMap<>();
		//襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		try {
			// 设置分页信息
			if (works.getiDisplayLength() == 0)
				works.setiDisplayLength(8); // 默认长度9
			if (works.getPageNo() <= 0)
				works.setPageNo(1); // 默认页数1
			works.setiDisplayStart((works.getPageNo() - 1)
					* works.getiDisplayLength()); // 显示起始索引
			works.setStatus("1");// 状态 0：无效，1：有效
			// 当关键字不为null并且不为空时，通过关键字全分类模糊查询
			// 反之，查询当前分页状态下的信息
			if (works.getKeyword() != null && !works.getKeyword().trim().isEmpty()) {
				resp.put("dataList",worksService.queryByLike(works, works.getKeyword()));
				resp.put("total",worksService.queryByLikeCount(works, works.getKeyword()));
			} else {
				List<Works> rs = worksService.query(works);
				resp.put("dataList", rs);
				resp.put("total",worksService.count(works));
				int lens = rs.size();
				List<Integer> numbersGAJ = new ArrayList<Integer>();
				List<Integer> numsGAJ = new ArrayList<Integer>();
				for(int i=0;i<lens;i++){
					Works temp = rs.get(i);
					String status = temp.getSignStatus();
					int cnt=0;
					if(status!=null && status!=""){
						cnt=status.split(",").length;//gaj signed
					}
					numbersGAJ.add(i, cnt);//公安局已签收数目
					String[] tempAs = temp.getAssociations();
//					String[] tempAs = temp.getDepars().split(",");
					int nums=0;
//					if(tempAs!=null){
						for(int j=0;j<tempAs.length;j++){
							if(tempAs[j] != null && !(tempAs[j].equals(";")) && !(tempAs[j].equals(""))){
								nums++;
							}
						}
//					}
					numsGAJ.add(i, nums);//公安局需要签收的单位数目
				}
				resp.put("numbersGAJ",numbersGAJ);
				resp.put("numsGAJ",numsGAJ);
			}
			resp.put("pageNo",works.getPageNo());
			resp.put("size",works.getiDisplayLength());
			resp.put("works",works);
			resp.put("key",works.getKeyword());
			resp.put("weekdays",weekdays);
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询重要工作异常", e);
		}
		return resp;
	}
	
	/**
	 * 按文件类型，
	 * 分类查询主要工作列表
	 * @param Works
	 * @return
	 */
	@RequestMapping("/queryBy")
	public ModelAndView queryByType(Works works, String fileTypes) {
		ModelAndView mv = new ModelAndView("/works/worksList.jsp");
		//襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
		
		try {
			// 设置分页信息
			if (works.getiDisplayLength() == 0)
				works.setiDisplayLength(24); // 默认长度9
			if (works.getPageNo() <= 0)
				works.setPageNo(1); // 默认页数1
			works.setiDisplayStart((works.getPageNo() - 1)
					* works.getiDisplayLength()); // 显示起始索引
			works.setStatus("1");// 状态 0：无效，1：有效
			works.setFileTypes(fileTypes);
			// 当关键字不为null并且不为空时，通过关键字全分类模糊查询
			// 反之，查询当前分页状态下的信息
			if (works.getKeyword() != null && !works.getKeyword().trim().isEmpty()) {
				mv.addObject("dataList",worksService.queryByLike(works, works.getKeyword()));
				mv.addObject("total", worksService.queryByLikeCount(works, works.getKeyword()));
			} else {
		//		mv.addObject("dataList", worksService.queryBy(works));
				mv.addObject("total", worksService.countBy(works));
				List<Works> dataList=worksService.queryBy(works);

				/*** 统计还要多少要签收  开始 */
				for(Works x : dataList){
					String status = x.getSignStatus();
					String[] zhiduis = null;
					String[] assos = x.getAssociations();
					List<String> realAssos = new ArrayList<String>();
					List<String> notAssos = new ArrayList<String>();
					int len = 0,cnt=0;
					//公安-签收状态有别于特警，直接加入签收用户名，用,逗号分隔
					if(status!=null && status!=""){
						zhiduis = status.split(",");//已签收单位String数组
					}
					int tempIndex=0;
					for(int i=0;i<assos.length;i++){
						if((assos[i]!=null)){
		 					realAssos.add(cnt, assos[i]);
							//未签收
							if(zhiduis!=null && zhiduis.length>0){
								int tempCnt=0;
								for(int it=0;it<zhiduis.length;it++){
									if(!(assos[i].equals(zhiduis[it]))){
										tempCnt++;
									}
								}
								if(tempCnt==zhiduis.length){
									notAssos.add(tempIndex, assos[i]);
									tempIndex++;
								}
							}else{
								notAssos.add(cnt, assos[i]);
							}
							cnt++;
						}
					}
					 if(realAssos.size()>0){
						 x.setSignStatus(notAssos.size()+"");//用这个字段迭代到前台			
						}else{
							x.setSignStatus("-1");
						}
					
				}
				/***  统计还要多少要签收  结束*/
				mv.addObject("dataList", dataList);
			}
			mv.addObject("pageNo", works.getPageNo());
			mv.addObject("size", works.getiDisplayLength());
			mv.addObject("works", works);
			mv.addObject("key", works.getKeyword()); 
			mv.addObject("fileTypes", fileTypes);//文件类型：1-7，对应不同模板
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return mv;
	}

	
	
	//useless flowings.
	/**
	 * 查询列表
	 * @param Works
	 * @return
	 */
	@RequestMapping("/myWorks")
	public ModelAndView myWorks(Works works) {
		ModelAndView mv = new ModelAndView("/my/myWorksInfo.jsp");
		try {
			Member mbo = (Member) session.getAttribute("user");
			if (mbo == null) {
				mv.setViewName("404.jsp");
			} else {
				works.setUserid(mbo.getId());
				// 设置分页信息
				if (works.getiDisplayLength() == 0)
					works.setiDisplayLength(10); // 默认长度5
				if (works.getPageNo() <= 0)
					works.setPageNo(1); // 默认页数1
				works.setiDisplayStart((works.getPageNo() - 1)
						* works.getiDisplayLength()); // 显示起始索引
				mv.addObject("dataList", worksService.query(works));
				mv.addObject("pageNo", works.getPageNo());
				mv.addObject("size", works.getiDisplayLength());
				mv.addObject("total", worksService.count(works));
				mv.addObject("works", works);
			}
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return mv;
	}

	/**
	 * 删除新闻
	 * @param Works
	 * @return
	 */
	@RequestMapping("/delWorks")
	public ModelAndView delWorks(Works works, Long id) {
		ModelAndView mv = new ModelAndView("redirect:/works/myWorks");
		try {
			Member mbo = (Member) session.getAttribute("user");
			if (mbo == null) {
				mv.setViewName("404.jsp");
			} else {
				worksService.delete(id);
			}
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return mv;
	}

	/**
	 * 初始化新闻
	 * @param Works
	 * @return
	 */
	@RequestMapping("/initWorks")
	public ModelAndView initWorks(Works works, Long id) {
		ModelAndView mv = new ModelAndView("/my/worksDetail.jsp");
		mv.addObject("column",
				this.confService.queryByType(null/*GlobalConstant.TYPE_Works*/, 9667L));
		Member mbo = (Member) session.getAttribute("user");
		if (mbo == null) {
			mv.setViewName("404.jsp");
		} else {
			works = worksService.find(id);
			mv.addObject("data", works);
		}
		return mv;
	}

	/**
	 * 保存新闻
	 * @param Works
	 * @return
	 */
	@RequestMapping("/saveWorks")
	public ModelAndView saveWorks(Works works) {
		ModelAndView mv = new ModelAndView("redirect:/works/myWorks");
		Member mbo = (Member) session.getAttribute("user");
		if (mbo == null) {
			mv.setViewName("404.jsp");
		} else {
			works.setUserid(mbo.getId());
			works.setCreateTime(DateUtil.getCurrentDate2());
			worksService.saveOrUpdate(works);
		}
		return mv;
	}

	/**
	 * 新增
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit() {
		return edit(null);
	}

	/**
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/works/editWorksDetail.jsp");
//		mv.addObject("data", id==null||id==0 ? id : this.worksService.find(id));
		//襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
		
		if(id==null || id==0){
		mv.addObject("data", id);
	}else{
		Works works = this.worksService.find(id);
		//投稿统计师将department置null,现将其复原到页面回显
		String[] nd = works.getAssociations();
		if(nd == null){
			String temp=works.getDepars();
			String[] st=temp.split(",");
			int cnt=st.length;
			String[] nds = new String[cnt-1];
			for(int i=1;i<cnt;i++){
				nds[i-1]=st[i];
			}
			works.setAssociations(nds);;
		}
		mv.addObject("data", works);
	}
		return mv;
	}

	/**
	 * 保存（更新）新闻
	 * @param news
	 * @return
	 */
	@RequestMapping("/adminSave")
	public ModelAndView save(Works works, Long pid) {
		ModelAndView mv = new ModelAndView("/works/worksOk.jsp");
		//将数组转化成String
//		String[] ds=works.getAssociations();
//		String deps = "";
//		for(int i=0;i<46;i++){
//			if(ds[i]==null || ds[i]=="")ds[i]=";";
//			deps += ","+ds[i];
//		}
//		works.setDepars(deps);
//		works.setAssociations(null);
		
		try {
			if(works.getId()==null) {
				// 新增通知通报
				if(works.getFalseCreateTime() == null || works.getFalseCreateTime() == ""){
					works.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
				this.worksService.save(works);
			} else {
				//更新修改通知通报
				// 新增通知通报
				if(works.getFalseCreateTime() == null || works.getFalseCreateTime() == ""){
					works.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
				this.worksService.update(works);
		    // 清理文章缓存
		    NginxPurgeCacheUtil.purge(2, works.getId());
			}
		} catch(Exception e) {
			BaseLog.e(getClass(), "保存异常！", e);
		}

		return mv;
	}
	
	/**
	 * 襄阳市公安局
	 * 签收通知通报：多个用户均需要签收
	 * @param id
	 * @param name 登录用户名 String
	 * @return
	 */
	@RequestMapping("/signed/{id}")
	public ModelAndView signeds(@PathVariable Long id, String name) {
		ModelAndView mv = new ModelAndView("/works/worksOk.jsp");
		Works data = this.worksService.find(id);
		
		String[] assos = data.getAssociations();
//		String[] assos = data.getDepars().split(",");//cnt
		int lens = assos.length;
		String statuses = data.getSignStatus();
		if(statuses==null){
			for(int iter=0;iter<lens;iter++){
				if(assos[iter]!=null && assos[iter].equals(name)){
					data.setSignStatus(name);//将状态1换成用户名
				}
			}
		}else{
			for(int iter=0;iter<lens;iter++){
				//同一账户重复签收无影响
				if(assos[iter]!=null && statuses.indexOf(name)==-1 && assos[iter].equals(name)){
					data.setSignStatus(statuses+","+name);
				}
			}
		}
		this.worksService.update(data);
		return mv;
	}
	
	/**
	   * 签收登陆
	   */
	  @RequestMapping("/login/{id}")
	  public ModelAndView loginMores(@PathVariable Long id) {
	    ModelAndView mv = new ModelAndView("/works/login.jsp");
	  //襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
	  		
		mv.addObject("id", id);
	    return mv;
	  }
	  
	  /**
		 * 襄阳市公安局
		 * 先验证登陆信息；通过后签收
		 * 签收通知通报：多个用户均需要签收
		 * @param id
		 * @param name 登录用户名 String
		 * @return
		 */
		@RequestMapping("/signes/{id}")
		public ModelAndView signeds(@PathVariable Long id, String username,String password) {
			ModelAndView mv = new ModelAndView("redirect:/works/show-"+id+".html");
			
			/*校验输入信息是否合法*/
			String str = "";//提示信息
			if(ValidationUtil.isEmpty(username)) {
				str = "请输入用户名";// 请输入用户名或手机号
			} else if(ValidationUtil.isEmpty(password)) {
				str = "请输入密码";// 请输入密码
			}
			if("".equals(str)) {
				User member = userService.findMemberByUsername(username);
				if(null != member) {
					if(SafeUtil.md5(password).substring(8, 16).equals(member.getPasswd())) {
						//登陆成功-则进行点击登录进行签收
						Works data = this.worksService.find(id);
						
//						String[] assos = data.getDepars().split(",");
						String[] assos = data.getAssociations();
						int lens = assos.length;
						String statuses = data.getSignStatus();
						if(statuses==null){
							for(int iter=0;iter<lens;iter++){
								if(assos[iter]!=null && assos[iter].equals(username)){
									data.setSignStatus(username);//将状态1换成用户名
								}
							}
						}else{
							for(int iter=0;iter<lens;iter++){
								//同一账户重复签收无影响 如果先签收jwbzb,接着签收jw此法出错
//								if(assos[iter]!=null && statuses.indexOf(username)==-1 && assos[iter].equals(username)){
								if(assos[iter]!=null && assos[iter].equals(username)){
									if (username.equals("jjzd")) {
										if(statuses.indexOf("gsjjzd")!=-1){//如果有
											if(statuses.indexOf("jjzd", statuses.indexOf("gsjjzd")+6) ==-1){//随后没有jw
												data.setSignStatus(statuses+","+username);
											}
										}else{
											data.setSignStatus(statuses+","+username);
										}
									}else{
										String strArry [] = statuses.split(",");
										List<String> list = Arrays.asList(strArry);
										if(!list.contains(username)){
											data.setSignStatus(statuses+","+username);
										}
									}
								}
							}
						}
						this.worksService.update(data);
					}else{
						//登陆失败
						
					}
				}
			}
			
			return mv;
		}
}
